import { Layout, Col, Row, Typography, Tag, Dropdown, Menu, Input, Tooltip, Modal, Avatar, Button, Form } from 'antd'
import React, { useRef, useState } from 'react'
import "./index.scss"
import { observer } from "mobx-react"
import {
    AppstoreOutlined,
    MenuUnfoldOutlined,
    MenuFoldOutlined,
    PieChartOutlined,
    DesktopOutlined,
    ContainerOutlined,
    MailOutlined,
    CaretDownOutlined,
    UserOutlined,
    PoweroffOutlined,
    ExclamationCircleOutlined,
    LockOutlined
} from '@ant-design/icons';
import myinfo from '../mobx/info';
import { roleList, toast } from '../../utils/common';
import { ajax } from '../../api';
import { baseURL } from '../../api/request';
import { Link } from 'react-router-dom';
import { reg } from '../../utils/validate';

const { Header } = Layout
const { Title } = Typography
function Head(props: any) {
    const { history } = props;
    const { userInfo, changeInfo, collapsed } = myinfo



    const files: any = useRef()
    const [show, setShow] = useState(false)
    const clickToUpload = () => {
        files.current.click()
    }
    const startUploadeFile = async () => {

        const file = files.current.files[0]
        console.log(file)
        const data = new FormData()
        data.append("avatar", file)

        let res: any = await ajax.uploadfile(data)
        if (res.code == 200) {
            // 修改后台
            ajax.changeinfo({
                avatar: res.path
            })
                .then(result => {
                    console.log(userInfo)
                    changeInfo({
                        ...JSON.parse(JSON.stringify(userInfo)),  // 解决Proxy 数据丢失的问题 
                        avatar: res.path,
                    })
                })
            // 修改前端

        }
    }
    const [form] = Form.useForm()

    const handleLogout = () => {
        Modal.confirm({
            title: '退出登录',
            icon: <ExclamationCircleOutlined />,
            content: '你真的确定要退出登录吗?',
            okText: '确认',
            cancelText: '取消',
            okType: 'danger',
            onOk: () => {
                sessionStorage.removeItem("autoken")
                history.push("/login")
                changeInfo({
                    role: 0,
                    username: '',
                    avatar: ''
                })
            },
            onCancel() {

            }
        });
    }
    const handleClose = () => {
        setShow(false)
    }
    const changePass = () => {
        form.validateFields()
            .then(async valid => {
                console.log(valid);
                let { code, result }: any = await ajax.changepass(valid)
                if (code == 200) {
                    history.push("/login")
                }
            })
            .catch(err => {
                toast.error("请输入正确的密码")
            })
    }
    const showModal = () => {
        setShow(true)
    }
    return (
        <Header style={{ background: "#fff", padding: '0 20px' }}>
            <Row style={{ width: '100%', display: 'flex', alignItems: "center", height: '100%', justifyContent: "center" }}>
                <Col span={7} className="flex">
                    <i onClick={() => myinfo.changeCollapsed(collapsed)} style={{ marginRight: 5, cursor: "pointer", fontSize: 14 }}>  {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined)}</i>
                    <Title style={{ color: "#f50", margin: 0 }} level={4}>千锋武汉教务管理系统</Title>

                </Col>
                <Col span={9} className='flex' style={{ justifyContent: "center" }}>
                    <div style={{ textAlign: "center" }}>
                        day day day - 今晚打老虎
                    </div>
                </Col>
                <Col span={8} style={{ padding: "0 10px", display: "flex", justifyContent: "center" }}>
                    {
                        userInfo && <div>
                            <Dropdown placement='bottomCenter' overlay={
                                () => (
                                    <Menu>
                                        <Menu.Item key={0}>
                                            <Link to={"/main/home"}>首&emsp;&emsp;页</Link>
                                        </Menu.Item>
                                        <Menu.Item key={1}>
                                            <Link to={"/main/infos"}>个人中心</Link>
                                        </Menu.Item>
                                        <Menu.Item key={2} onClick={showModal}>
                                            修改密码
                                        </Menu.Item>
                                    </Menu>
                                )
                            }>
                                <span style={{ padding: "0 15px" }}>{userInfo.username} <CaretDownOutlined></CaretDownOutlined></span>

                            </Dropdown>
                            <Tag style={{ margin: "0 10px" }} color={roleList.find((item) => item.value == userInfo.role)?.color}>{roleList.find((item) => item.value == userInfo.role)?.text}</Tag>
                            <Tooltip style={{ margin: "0 10px" }} placement="top" title={"切换头像"}>
                                <input type="file" style={{ display: "none" }} ref={files} onChange={startUploadeFile}></input>
                                {
                                    userInfo.avatar ? <img onClick={clickToUpload} style={{ border: "1px solid #999", margin: "0 10px", cursor: 'pointer', width: 36, height: 36, borderRadius: '50%', display: 'inline-block' }} src={userInfo.avatar.replace(/public/, baseURL)} />
                                        :
                                        <i onClick={clickToUpload} style={{ margin: "0 10px", cursor: "pointer", width: 36, height: 36, background: "#999", display: "inline-block", borderRadius: "50%", textAlign: "center", lineHeight: "36px" }}  >{<UserOutlined style={{ fontSize: "18px", color: "#fff" }} />}</i>
                                }

                            </Tooltip>
                            <Tooltip placement='top' title={"退出登录"}>
                                <Button onClick={handleLogout} shape='circle' danger icon={<PoweroffOutlined />}></Button>

                            </Tooltip>
                        </div>
                    }

                </Col>
            </Row >
            <Modal
                title={'修改密码 (' + userInfo?.username + ')'}
                visible={show}
                onCancel={handleClose}
                onOk={changePass}
                width={'40%'}
                okText="修改密码"
                cancelText="取消修改"
            >
                <Form
                    name="basic"
                    autoComplete="off"
                    form={form}
                    layout={'horizontal'}
                    labelCol={{ span: 24 }}
                    wrapperCol={{ span: 24 }}

                >
                    <Form.Item
                        label="旧密码"
                        name="oldpass"
                        rules={[
                            { required: true, message: '请输入原始密码!' },
                            { pattern: reg.pwd, message: "请输入6-16位的数字加字母组合" }
                        ]}
                    >

                        <Input.Password prefix={<LockOutlined className="site-form-item-icon" />} placeholder="请输入旧密码" />
                    </Form.Item>
                    <Form.Item
                        label="新密码"
                        name="newpass"
                        rules={[
                            { required: true, message: '请输入新密码!' },
                            { pattern: reg.pwd, message: "请输入6-16位的数字加字母组合" }
                        ]}
                    >

                        <Input.Password prefix={<LockOutlined className="site-form-item-icon" />} placeholder="请输入新密码" />
                    </Form.Item>
                </Form>
            </Modal>
        </Header>
    )
}

export default
    (observer(Head))